﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WxYygh.Common;
using WxYygh.Models;


namespace WxYygh.Controllers
{
    public class WeChatCheckAttribute : ActionFilterAttribute
    {
        public string appID = ConfigurationManager.AppSettings["appID"];
        public string AppSecret = ConfigurationManager.AppSettings["AppSecret"];
        //执行Action之前操作
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                //HttpContext.Current.Session["openid"] = "oScoIjxjjDuk6m_7iaexLjSdEG1o";
                //判断是否登录或是否用权限，如果有那么就进行相应的操作，否则跳转到登录页或者授权页面
                if (HttpContext.Current.Session["openid"] != null)
                {
                    //处理Action之前操作内容根据我们提供的规则来定义这部分内容
                    base.OnActionExecuting(filterContext);
                }
                else
                {
                   
                    string redirect_uri = HttpContext.Current.Request.Url.AbsoluteUri;

                    if (string.IsNullOrEmpty(HttpContext.Current.Request["code"]))
                    {
                        string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect", ConfigurationManager.AppSettings["appID"], redirect_uri);

                        HttpContext.Current.Response.Redirect(url);

                    }
                    else if (!string.IsNullOrEmpty(HttpContext.Current.Request["code"]))
                    {
                        string code = HttpContext.Current.Request["code"];
                        string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appID, AppSecret, code);

                        string responseText = HttpHelper.Instance.get(url);

                        UserInfo codeEn = JsonHelper.GetEntity<UserInfo>(responseText);

                        HttpContext.Current.Session["openid"] = codeEn.openid;
                        

                        base.OnActionExecuting(filterContext);

                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message);
            }
        }

        
    }
}